package com.example.inventory.request;

import com.example.inventory.model.ProductInventory;
import com.example.inventory.service.ProductInventoryService;

/**
 * 重新加载商品库存的缓存
 * @author james
 */
public class ProductInventoryCacheRefreshRequest implements Request {

    /**
     * 任务名称, 用于调试
     */
    private String taskName;

    /**
     * 商品id
     */
    private Integer productId;
    /**
     * 商品库存Service
     */
    private ProductInventoryService productInventoryService;

    /**
     * 强制刷新标记位
     */
    private boolean forceRefresh;

    public ProductInventoryCacheRefreshRequest(String taskName,Integer productId, ProductInventoryService productInventoryService, boolean forceRefresh) {
        this.taskName = taskName;
        this.productId = productId;
        this.productInventoryService = productInventoryService;
        this.forceRefresh = forceRefresh;
    }

    /**
     * 重新加载商品库存的缓存
     */
    @Override
    public void process() {
        // 从db查询最新的商品缓存数量
        ProductInventory productInventory = productInventoryService.findProductInventory(productId);
        // System.out.println("=============log==============:已经查询到商品最新的库存数量,商品Id:"+productId+",商品库存数量="+productInventory.getInventoryCnt()
        // +" 开始刷新到redis中");
        // 将最新的商品库存数量, 更新到redis缓存中
        productInventoryService.setProductInCache(productInventory);
        // System.err.println("在执行任务["+taskName+"],productId=["+productId+"],已经从数据库读取,并更新到redis中");
    }

    @Override
    public Integer getProductId() {
        return productId;
    }

    @Override
    public boolean isForceRefresh() {
        return forceRefresh;
    }

    @Override
    public String getTaskName() {
        return taskName;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("ProductInventoryCacheRefreshRequest{");
        sb.append("taskName='").append(taskName).append('\'');
        sb.append(", productId=").append(productId);
        sb.append(", productInventoryService=").append(productInventoryService);
        sb.append(", forceRefresh=").append(forceRefresh);
        sb.append('}');
        return sb.toString();
    }
}
